package com.srwl.mytx.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TaskRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.service.TaskService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TaskRecordActivity extends BaseActivity {
    private static final String TAG = "TaskRecordActivity";
    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private TaskRecordAdapter taskRecordAdapter;
    private List<Task> taskList = new ArrayList<>();
    private int page = 1;
    private boolean hasNextPage;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_record);
        refreshLayout = findViewById(R.id.refresh_layout);
        recyclerView = findViewById(R.id.rv_task);
        progressBar = findViewById(R.id.progress_bar);
        taskRecordAdapter = new TaskRecordAdapter(this, taskList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(taskRecordAdapter);
        initRefreshLayout();
        loadData(true, false);
    }

    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", 10);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .queryReceiveTask(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            taskRecordAdapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            taskRecordAdapter.showErrorView();
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: " + pageInfo.toString());
                        pageInfo.getInteger("total");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(TaskRecordActivity.this)), 2000);
                        }
                        if (isRefresh) {
                            taskList.clear();
                            page = 0;
                        }
                        List<Task> donations = pageInfo.getJSONArray("list").toJavaList(Task.class);
                        if (donations.size() != 0) {
                            taskList.addAll(donations);
                            taskRecordAdapter.showNormalView();
                            page++;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        taskRecordAdapter.showErrorView();

                    }
                });

    }

    private void initRefreshLayout() {
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                page = 1;
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

}
